import React, { useState, useRef } from 'react';
import './CourseUpload.module.css';

const CourseUpload = () => {
  const [courseData, setCourseData] = useState({
    name: '',
    description: '',
    price: '',
    coverImageUrl: '',
    teacherId: '',
    teacherName: '',
    uploaderUsername: ''
  });
  
  const [uploadProgress, setUploadProgress] = useState({
    video: 0,
    images: 0
  });
  
  const [uploadedFiles, setUploadedFiles] = useState({
    videoUrls: [],
    imageUrls: []
  });
  
  const [isUploading, setIsUploading] = useState(false);
  const [message, setMessage] = useState('');
  
  const videoFileRef = useRef();
  const imageFilesRef = useRef();
  
  const API_BASE_URL = 'http://localhost:3001/api';
  
  // 处理表单输入变化
  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setCourseData(prev => ({
      ...prev,
      [name]: value
    }));
  };
  
  // 上传大文件视频
  const uploadLargeVideo = async (file) => {
    const formData = new FormData();
    formData.append('video', file);
    
    try {
      const token = localStorage.getItem('token');
      const response = await fetch(`${API_BASE_URL}/upload-large-video`, {
        method: 'POST',
        headers: {
          'Authorization': token ? (token.startsWith('Bearer ') ? token : `Bearer ${token}`) : ''
        },
        body: formData
      });
      
      const result = await response.json();
      
      if (result.success) {
        setUploadedFiles(prev => ({
          ...prev,
          videoUrls: [...prev.videoUrls, result.data.url]
        }));
        setMessage('视频上传成功！');
      } else {
        setMessage(`视频上传失败: ${result.message}`);
      }
    } catch (error) {
      setMessage(`视频上传错误: ${error.message}`);
    }
  };
  
  // 上传大文件图片
  const uploadLargeImages = async (files) => {
    const formData = new FormData();
    Array.from(files).forEach(file => {
      formData.append('images', file);
    });
    
    try {
      const token = localStorage.getItem('token');
      const response = await fetch(`${API_BASE_URL}/upload-large-images`, {
        method: 'POST',
        headers: {
          'Authorization': token ? (token.startsWith('Bearer ') ? token : `Bearer ${token}`) : ''
        },
        body: formData
      });
      
      const result = await response.json();
      
      if (result.success) {
        setUploadedFiles(prev => ({
          ...prev,
          imageUrls: [...prev.imageUrls, ...result.data.urls]
        }));
        setMessage('图片上传成功！');
      } else {
        setMessage(`图片上传失败: ${result.message}`);
      }
    } catch (error) {
      setMessage(`图片上传错误: ${error.message}`);
    }
  };
  
  // 处理视频文件选择
  const handleVideoSelect = (e) => {
    const file = e.target.files[0];
    if (file) {
      uploadLargeVideo(file);
    }
  };
  
  // 处理图片文件选择
  const handleImageSelect = (e) => {
    const files = e.target.files;
    if (files.length > 0) {
      uploadLargeImages(files);
    }
  };
  
  // 提交课程
  const handleSubmit = async (e) => {
    e.preventDefault();
    setIsUploading(true);
    setMessage('');
    
    try {
      const coursePayload = {
        ...courseData,
        videoUrls: uploadedFiles.videoUrls,
        imageUrls: uploadedFiles.imageUrls,
        price: parseInt(courseData.price) || 0
      };
      
      const token = localStorage.getItem('token');
      const response = await fetch(`${API_BASE_URL}/add-course`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': token ? (token.startsWith('Bearer ') ? token : `Bearer ${token}`) : ''
        },
        body: JSON.stringify(coursePayload)
      });
      
      const result = await response.json();
      
      if (result.success) {
        setMessage('课程添加成功！');
        // 重置表单
        setCourseData({
          name: '',
          description: '',
          price: '',
          coverImageUrl: '',
          teacherId: '',
          teacherName: '',
          uploaderUsername: ''
        });
        setUploadedFiles({
          videoUrls: [],
          imageUrls: []
        });
      } else {
        setMessage(`课程添加失败: ${result.message}`);
      }
    } catch (error) {
      setMessage(`课程添加错误: ${error.message}`);
    } finally {
      setIsUploading(false);
    }
  };
  
  return (
    <div className="course-upload">
      <h2>课程上传</h2>
      
      {message && (
        <div className={`message ${message.includes('成功') ? 'success' : 'error'}`}>
          {message}
        </div>
      )}
      
      <form onSubmit={handleSubmit}>
        <div className="form-group">
          <label>课程名称:</label>
          <input
            type="text"
            name="name"
            value={courseData.name}
            onChange={handleInputChange}
            required
          />
        </div>
        
        <div className="form-group">
          <label>课程描述:</label>
          <textarea
            name="description"
            value={courseData.description}
            onChange={handleInputChange}
            rows="4"
            required
          />
        </div>
        
        <div className="form-group">
          <label>课程价格:</label>
          <input
            type="number"
            name="price"
            value={courseData.price}
            onChange={handleInputChange}
            min="0"
          />
        </div>
        
        <div className="form-group">
          <label>封面图片URL:</label>
          <input
            type="text"
            name="coverImageUrl"
            value={courseData.coverImageUrl}
            onChange={handleInputChange}
            required
          />
        </div>
        
        <div className="form-group">
          <label>教师ID:</label>
          <input
            type="text"
            name="teacherId"
            value={courseData.teacherId}
            onChange={handleInputChange}
            required
          />
        </div>
        
        <div className="form-group">
          <label>教师姓名:</label>
          <input
            type="text"
            name="teacherName"
            value={courseData.teacherName}
            onChange={handleInputChange}
            required
          />
        </div>
        
        <div className="form-group">
          <label>上传者用户名:</label>
          <input
            type="text"
            name="uploaderUsername"
            value={courseData.uploaderUsername}
            onChange={handleInputChange}
            required
          />
        </div>
        
        <div className="upload-section">
          <h3>文件上传</h3>
          
          <div className="form-group">
            <label>上传视频文件 (支持大文件):</label>
            <input
              type="file"
              ref={videoFileRef}
              onChange={handleVideoSelect}
              accept="video/*"
            />
            <p className="help-text">支持MP4、MOV、AVI、WMV、FLV、MKV格式，最大2GB</p>
          </div>
          
          <div className="form-group">
            <label>上传图片文件 (支持大文件):</label>
            <input
              type="file"
              ref={imageFilesRef}
              onChange={handleImageSelect}
              accept="image/*"
              multiple
            />
            <p className="help-text">支持JPEG、PNG、GIF、WebP格式，最大2GB</p>
          </div>
          
          {uploadedFiles.videoUrls.length > 0 && (
            <div className="uploaded-files">
              <h4>已上传的视频:</h4>
              <ul>
                {uploadedFiles.videoUrls.map((url, index) => (
                  <li key={index}>{url}</li>
                ))}
              </ul>
            </div>
          )}
          
          {uploadedFiles.imageUrls.length > 0 && (
            <div className="uploaded-files">
              <h4>已上传的图片:</h4>
              <ul>
                {uploadedFiles.imageUrls.map((url, index) => (
                  <li key={index}>{url}</li>
                ))}
              </ul>
            </div>
          )}
        </div>
        
        <button 
          type="submit" 
          disabled={isUploading}
          className="submit-btn"
        >
          {isUploading ? '上传中...' : '添加课程'}
        </button>
      </form>
    </div>
  );
};

export default CourseUpload; 